package com.sora.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sora.basic.exception.BusinessException;
import com.sora.basic.jwt.JwtUtils;
import com.sora.basic.jwt.LoginData;
import com.sora.basic.jwt.RsaUtils;
import com.sora.basic.service.impl.BaseServiceImpl;
import com.sora.basic.util.AjaxResult;
import com.sora.basic.util.HttpUtil;
import com.sora.basic.util.Md5Utils;
import com.sora.basic.util.StrUtils;
import com.sora.sys.domain.Menu;
import com.sora.user.constant.WxConstants;
import com.sora.user.domain.Logininfo;
import com.sora.user.domain.User;
import com.sora.user.domain.Wxuser;
import com.sora.user.dto.LoginDto;
import com.sora.user.mapper.LogininfoMapper;
import com.sora.user.mapper.UserMapper;
import com.sora.user.mapper.WxuserMapper;
import com.sora.user.service.ILogininfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;


    @Override
    public Map<String, Object> loginAccount(LoginDto loginDto) {
        //1.校验空值
        if (StringUtils.isEmpty(loginDto.getAccount()) || StringUtils.isEmpty(loginDto.getCheckPass())) {
            throw new BusinessException("登录信息不能为空！");
        }

        //2.校验账户是否存在
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo == null) {
            throw new BusinessException("该账号没有被注册过，请注册！");
        }

        //3.校验密码是否正确
        String salt = logininfo.getSalt();
        String inputMD5Pwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + salt);
        if (!inputMD5Pwd.equals(logininfo.getPassword())) {
            throw new BusinessException("密码不正确！");
        }

        //4.校验是否禁用
        if (!logininfo.getDisable()) {
            throw new BusinessException("该账户已经被禁用，请联系管理员解封！");
        }

        //----------------------------------------------
        //以前的无状态token方案
        /*//5.将登录信息保存在redis，设置30分钟有效期，随机生成key值
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);

        //6.返回信息：1.key - 后续发送请求都要携带者个token值，用于验证是否登录过了 2.登录信息 - 前端页面展示用户信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("token", token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo", logininfo);*/
        //----------------------------------------------

        return loginSuccessJwtHandler(logininfo);
    }

    @Override
    public AjaxResult loginWechat(Map<String, String> map) {
        //准备的参数appid，secret，code  -  第二次请求返回的参数 token，openid
        //1.准备第二个请求的地址
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID).replace("SECRET", WxConstants.SECRET)
                .replace("CODE", map.get("code"));

        //2.调用httpUtils 发送微信登录的请求：返回json的字符串
        String jsonStr = HttpUtil.httpGet(url);

        //3.通过fastJson将返回的json格式的字符串转化为json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //4.通过openid判断是否为第一次扫码登录(通过openid查询t_wxuser表)
        Wxuser wxuser = wxuserMapper.loadByOpenId(openid);
        if (wxuser != null) {
            //4.1如果查询出结果 - 表示不是第一次扫码登录 - 免密登录：返回true，token，logininfo对象

            User user = userMapper.loadById(wxuser.getUserId());
            Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());

            //----------------------------------------------
            //以前的无状态token方案
            /*//将登录信息保存在redis，设置30分钟有效期，随机生成key值
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);

            //6.返回信息：1.key - 后续发送请求都要携带者个token值，用于验证是否登录过了 2.登录信息 - 前端页面展示用户信息
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("token", token);
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            resultMap.put("logininfo", logininfo);*/
            //----------------------------------------------

            Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);

            return new AjaxResult(true, resultMap);
        }
        //4.2如果查询不到结果 - 表示是第一次扫码登录 - 拼装请求参数(?access_token=ACCESS_TOKEN&openid=OPENID)
        return new AjaxResult(false, "?access_token=" + access_token + "&" + "openid=" + openid);
    }

    @Override
    public AjaxResult loginWechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String access_token = map.get("accessToken");
        String openid = map.get("openId");
        //1.校验-空值
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("输入的信息不能为空！");
        }

        //2.校验-手机验证码：是否过期，是否正确
        //是否过期
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj == null) {
            throw new BusinessException("验证码已经过期了！");
        }
        //是否正确
        if(!obj.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("验证码不正确！");
        }

        //3.准备第三个请求
        // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);

        //4.使用HttpUtil发送微信绑定请求 - 获取微信用户信息：返回jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        
        //5.使用fastJson处理jsonStr - 将jsonObj中的数据转换Wxuser对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = jsonObject2Wxuser(jsonObject);

        //6.创建User对象和Logininfo对象【phone】 - 难度
        //7.添加数据库：Logininfo对象 - User对象 - Wxuser对象
        //注意：该用户可能通过手机注册过，但是没有绑定微信
        User user = userMapper.loadByPhone(phone);
        if(user == null){//代表没有用手机号码注册过
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            //添加logininfo对象生成自增长id
            logininfoMapper.save(logininfo);
            //将生成的自增长id添加到user对象中
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        //将user对象的自增长id添加到t_wxuser表中
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);

        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());

        //----------------------------------------------
        //以前的无状态token方案
        /*//8.做免密登录
        //将登录信息保存在浏览器的本地存储
        String token = UUID.randomUUID().toString();
        //有可能通过手机号码注册过，所以不使用logininfo的id
        redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("token",token);
        resultMap.put("logininfo",logininfo);*/
        //----------------------------------------------

        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);

        return new AjaxResult(true,resultMap);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(12);
        String Md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(Md5Pwd);
        user.setState(1);
        return user;
    }

    private Wxuser jsonObject2Wxuser(JSONObject jsonObject) {
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }


    public Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        Map<String,Object> map = new HashMap<>(); // 传递给前端的数据
        LoginData loginData = new LoginData(); //给Jwt加密的

        //1.设置logininfo
        //为了保证安全，将盐值和密码置空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);

        //设置menus和permissions
        if(logininfo.getType() == 0){ //代表员工
            //设置permissions
            List<String> permissions = logininfoMapper.findPermissionsByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);

            //设置menus
            List<Menu> menus = logininfoMapper.findMenusByLogininfoId(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }

        //调用Jwt工具类进行加密
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }
}
